package cn.edu.jxau.core.util;

import cn.edu.jxau.core.Constant;
import cn.edu.jxau.core.exception.FrameException;
import cn.edu.jxau.core.web.FormFieldParam;
import cn.edu.jxau.core.web.FileFieldParam;
import cn.edu.jxau.core.web.Param;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Desc:
 * ------------------------------------
 * Author:fulei04@meituan.com
 * Date:2017/12/24
 * Time:上午10:51
 */
public class UploadUtils {

    private static final int _1M = 1024 * 1024;
    private static ServletFileUpload servletFileUpload;

    public static void init(ServletContext servletContext) {

        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        servletFileUpload = new ServletFileUpload(
                new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
        int uploadLimit = Constant.UPLOAD_LIMIT;
        if (uploadLimit <= 0) {
            throw new FrameException("未成功配置uploadLimit参数");
        }
        servletFileUpload.setFileSizeMax(uploadLimit * _1M);
    }

    public static boolean isMultipart(HttpServletRequest request) {
        return ServletFileUpload.isMultipartContent(request);
    }

    public static Param getParam(HttpServletRequest request) throws FileUploadException, IOException {

        List<FileFieldParam> fileFieldParamList = new ArrayList<>();
        List<FormFieldParam> formFieldParamList = new ArrayList<>();
        List<FileItem> fileItemList = servletFileUpload.parseRequest(request);
        for(FileItem fileItem : fileItemList) {
            if(fileItem.isFormField()) {
                formFieldParamList.add(new FormFieldParam(fileItem.getName(),fileItem.getString("UTF-8")));
            } else {
                String fieldName = fileItem.getFieldName();
                String fileName = getFileName(fileItem);
                long fileSize = fileItem.getSize();
                String contentType = fileItem.getContentType();
                InputStream input = fileItem.getInputStream();
                fileFieldParamList.add(new FileFieldParam(fieldName,fileName,fileSize,contentType,input));
            }
        }
        return new Param(formFieldParamList,fileFieldParamList);
    }

    private static String getFileName(FileItem fileItem) {
        String path = fileItem.getName();
        return path.substring(path.lastIndexOf(File.separator)+1);
    }

    public static void upload(String dirPath,FileFieldParam fileFieldParam) throws IOException {

        File to = new File(dirPath+File.separator+fileFieldParam.getFileName());
        System.out.println("---"+to.getAbsolutePath());
        try(InputStream inputStream = fileFieldParam.getInput();
            BufferedInputStream in = new BufferedInputStream(inputStream);
            OutputStream outputStream = new FileOutputStream(to);
            BufferedOutputStream out = new BufferedOutputStream(outputStream)) {
            int temp = 0;
            while((temp = in.read())>=0) {
                out.write(temp);
            }
        } catch(IOException e) {
            throw new IOException("文件上传失败",e);
        }
    }

    public static void upload(String dirPath,List<FileFieldParam> fileFieldParamList) throws IOException {

        if(fileFieldParamList == null) {
            throw new NullPointerException("参数fileFieldParam为空");
        }
        for(FileFieldParam fileFieldParam : fileFieldParamList) {
            upload(dirPath,fileFieldParam);
        }
    }
}